import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: () => import('@/components/LayoutPage/LayoutPage'),
    meta: {
      name: '首页',
    },
    redirect: '/home',
    children: [
      {
        path: '/',
        name: 'home',
        meta: {
          name: '首页',
        },
        component: () => import('@/views/HomePage/HomePage'),
      },
      {
        path: 'article',
        name: 'article',
        meta: {
          name: '内容管理',
        },
        component: () => import('@/views/ArticlePage/ArticlePage'),
      },
      {
        path: 'publish',
        name: 'publish',
        meta: {
          name: '发布文章',
        },
        props: route => ({ articleId: route.query.id }),
        component: () => import('@/views/PublishPage/PublishPage'),
      },
    ],
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/LoginPage/LoginPage'),
    meta: {
      name: '登录',
    },
  },
]

const router = new VueRouter({
  routes,
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const token = store.state.user.token
  if (to.name !== 'login' && !token) next({ name: 'login' })
  else next()
})

export default router
